package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public String uploading(MultipartFile file) throws IOException {
        //判断传入的类型是否是bpmn文件
        String extension = FileUploadUtils.getExtension(file);
        if (!extension.endsWith("bpmn")){
            throw new BusinessException("请上传bpmn文件");
        }
        String path = FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
        return path;
    }

    @Override
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        //根据传进来的路径找到文件
        File file  = new File(SystemConfig.getProfile(),path);
        //将文件部署到activiti中
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, new FileInputStream(file))
                .deploy();
        //将数据获取到然后插入到bpmnInfo表中
        //新建一个bpmnInfo对象将数据封装进去
        BpmnInfo bpmnInfo = new BpmnInfo();
        //设置最容易拿到的两个参数
        bpmnInfo.setInfo(info);
        bpmnInfo.setBpmnType(bpmnType);
        //设置部署对象中的id和部署时间
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());
        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        //设置流程定义对象的 id key 和bpmn的名字
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setBpmnName(processDefinition.getName());

        //将数据插入到数据库中
        bpmnInfoMapper.insert(bpmnInfo);

    }

    @Override
    @Transactional
    public InputStream readResource(String deploymentId, String type) {
        //从数据库中获取到流程定义文件然后转化成输入流返回出去
        //根据类型判断需要返回的数据
        InputStream inputStream = null;
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploymentId).singleResult();
        if ("xml".endsWith(type)){
            //获取流程定义对象
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else {
            ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
            inputStream = processDiagramGenerator.generateDiagram(repositoryService.getBpmnModel(processDefinition.getId()),
                    Collections.EMPTY_LIST,
                    Collections.EMPTY_LIST,
                    "宋体",
                    "宋体",
                    "宋体");
        }
        return inputStream;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //根据id获取bpmnInfo的数据
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //删除bpmnInfo表中的数据
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //删除actviti的表中的数据
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId());
        //删除资源文件
        File file = new File(SystemConfig.getProfile(),processDefinition.getResourceName());
        if (file.exists()){
//            System.gc();
            file.delete();
        }
    }

    @Override
    public List<BpmnInfo> queryByBpmnType(String type) {
        return bpmnInfoMapper.queryByBpmnType(type);
    }
}
